export default {
  state: {
    cart: [] // 购物车数组
  },
  getters: {},
  mutations: {
    // 更新状态：购物车
    SET_CART (state, payload) {
      state.cart = payload
    }
  },
  actions: {
    // 添加购物车
    addTocart (store, currentProduct) {
      let cart = [...store.state.cart]
      const isok = cart.some(item => item.id === currentProduct.id)
      if (isok) {
        cart = cart.map(item => {
          if (item.id === currentProduct.id) {
            item.count += currentProduct.count
          }
          return item
        })
      } else {
        cart = [
          ...cart,
          currentProduct
        ]
      }
      store.commit('SET_CART', cart)
    },
    removeItem (store, id) {
      let cart = [...store.state.cart]
      cart = cart.filter(item => item.id !== id)
      store.commit('SET_CART', cart)
    }
  }
}
